<!--  -->
<template>
  <button @click="displaySpan">click</button>
  <div class="root" ref="rootRef" @click="rootClick">
    <template v-for="span of showSpanList" :key="span.key">
      <span
        :class="span.class"
        :position="span.index"
        :tag="span.key"
        v-bind="span.other"
        >{{ span.text }}</span
      >
    </template>
  </div>
</template>

<script lang='ts' setup>
import { onUnmounted, ref, watch } from "vue";
const rootRef = ref<HTMLDivElement | undefined>();
const showSpanList = ref();
const Selection: Selection = window.getSelection()!;
const props = withDefaults(defineProps<{ content: string }>(), {
  content: "",
});

const drawBg = function drawBg(start: number, end: number) {
  console.log(start, end);

  for (let index = start; index <= end; index++) {
    const span = showSpanList.value[index];
    span.class.push("hover");
  }
};
const displaySpan = function displaySpan() {
  const spans = Array.from(rootRef.value!.children);
  const start = Selection.anchorNode?.parentElement;
  const end = Selection.focusNode?.parentElement;
  const startIndex = spans.findIndex((v) => v === start);
  const endIndex = spans.findIndex((v) => v === end);
  const startItem = showSpanList.value[startIndex];
  const endItem = showSpanList.value[endIndex];
  drawBg(startIndex, endIndex);
  showSpanList.value.splice(endIndex + 1, 0, {
    text: "问题",
    class: ["base", "question"],
    type: "question",
    key: (Math.random() * 10).toString(36),
    other: {
      posi: Math.random(),
      linkStart: startIndex,
      linkEnd: endIndex,
    },
  });
};
const parse = function parse(content: string) {
  showSpanList.value = content.split("").map((v, index) => {
    return {
      text: v,
      index,
      class: ["class"],
      other: {},
      key: (Math.random() * 10).toString(36),
    };
  });
};

const rootClick = function rootClick(event: MouseEvent) {
  if ((event.target as Element).classList.contains("question")) {
    const tag = (event.target as HTMLDivElement).getAttribute("tag");
    const links = showSpanList.value.find((v: any) => v.key === tag);
    for (let index = links.other.linkStart; index <= links.other.linkEnd; index++) {
      const span = showSpanList.value[index];
      span.class.push("line");
    }
  }
};

// const igntion = function igntion() {};
// const turbofan = function turbofan() {};

const unWatch: Function = watch(
  () => props.content,
  (content) => {
    if (content) {
      parse(content);
    }
  },
  {
    immediate: true,
  }
);

onUnmounted(() => {
  unWatch && unWatch();
});
</script>
<style scoped>
.question {
  display: inline-block;
  padding: 4px;
  background: rgba(0, 0, 0, 0.5) !important;
  cursor: pointer;
}
.hover {
  background: pink;
}
.line{
  text-decoration: underline;
}
</style>